{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Find Similar API\n",
    "\n",
    "\n",
    "##  1.Create facelist 创建并命名facelist为xzq_test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "200"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import requests #导入requests模块\n",
    "import json\n",
    "# 1、create 创建一个装相片的列表\n",
    "create_facelists_url = \"https://face-ll.cognitiveservices.azure.com/face/v1.0/facelists/{faceListId}\" \n",
    "subscription_key = \"13a8027eaa9944f1b6885cdaaa74e878\"\n",
    "assert subscription_key\n",
    "headers = {\n",
    "    'Content-Type': 'application/json',\n",
    "    'Ocp-Apim-Subscription-Key': subscription_key,\n",
    "}\n",
    "data = {\n",
    "    \"name\": \"find_similar\",\n",
    "    \"userData\": \"薛之谦和谁最像？\",\n",
    "    \"recognitionModel\": \"recognition_02\"\n",
    "}\n",
    "params = {\n",
    "\n",
    "    \"faceListId\":\"xzq_test\"\n",
    "    \n",
    "\n",
    "}\n",
    "r_create = requests.put(create_facelists_url,headers=headers,params=params,json=data)\n",
    "# 请求成功，返回空字符串\n",
    "r_create.status_code"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2、Add face 添加至少10张face作为对比人脸数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 封装函数AddFace，以便添加人脸数据\n",
    "def AddFace(img_url=str,userData=str):\n",
    "    add_face_url =\"https://face-ll.cognitiveservices.azure.com/face/v1.0/facelists/{faceListId}/persistedFaces\"\n",
    "    subscription_key = \"13a8027eaa9944f1b6885cdaaa74e878\"\n",
    "    assert subscription_key\n",
    "    headers = {\n",
    "        'Content-Type': 'application/json',\n",
    "        'Ocp-Apim-Subscription-Key': subscription_key,\n",
    "    }\n",
    "    img_url = img_url\n",
    "\n",
    "    params_add_face={\n",
    "        \"faceListId\":\"xzq_test\",\n",
    "        \"userData\":userData\n",
    "    }\n",
    "    r_add_face = requests.post(add_face_url,headers=headers,params=params_add_face,json={\"url\":img_url})\n",
    "    return r_add_face.status_code #返回出状态码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "200"
      ]
     },
     "execution_count": 84,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#添加10张人脸照片\n",
    "AddFace(\"https://tse1-mm.cn.bing.net/th?id=OIP.POwccik2pNX0kB-PR1Mp-AHaHa&pid=Api&rs=1\",\"许嵩\")\n",
    "AddFace(\"http://img2.utuku.china.com/650x0/ent/20180524/0f71e5e9-8248-4352-af06-010620820d03.jpg\",\"易烊千玺\")\n",
    "AddFace(\"http://img5.cache.netease.com/photo/0003/2014-09-05/A5CH65N200AJ0003.jpg\",\"张若昀\")\n",
    "AddFace(\"https://alcdn.img.xiaoka.tv/20171122/99c/8a4/69877133/99c8a415e170bfc695f0fd0eaa737b77.jpg@1e_1c_0o_0l_600h_800w_90q_1pr.jpg\",\"张新成\")\n",
    "AddFace(\"http://www.tianya999.com/uploads/allimg/190725/2317-1ZH5162H6.jpg\",\"李现\")\n",
    "AddFace(\"http://n.sinaimg.cn/ent/transform/20160107/Yy0A-fxnkkux0921531.jpg\",\"大张伟\")\n",
    "AddFace(\"https://pic.baike.soso.com/p/20121004/20121004221558-1903292788.jpg\",\"朱桢\")\n",
    "AddFace(\"https://gss1.bdstatic.com/9vo3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D500/sign=08c51c40584e9258a23486eeac83d1d1/9345d688d43f8794a524bc0adc1b0ef41bd53a3e.jpg\",\"刘维\")\n",
    "AddFace(\"http://www.jvnan.com/uploads/160630/2_233457_1.jpg\",\"高磊鑫\")\n",
    "AddFace(\"https://pic.dbw.cn/003/008/062/00300806292_301975f4.jpg\",\"何炅\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 3、get查看facelists中的信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get facelist\n",
    "def GetFacelist():\n",
    "    get_facelist_url = \"https://face-ll.cognitiveservices.azure.com/face/v1.0/facelists/{faceListId}\"\n",
    "    data = {\n",
    "        \"faceListId\":\"xzq_test\",\n",
    "    }\n",
    "    r_get_facelist = requests.get(get_facelist_url,headers=headers,params=data)\n",
    "    return r_get_facelist.json()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4、Detect 检测出你需要的人脸并获取faceid\n",
    "[detect文档](https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'[{\"faceId\": \"d76c2a50-c7ad-4685-aa9d-1da0cc7e917a\", \"faceRectangle\": {\"top\": 95, \"left\": 191, \"width\": 126, \"height\": 126}, \"faceAttributes\": {\"smile\": 0.0, \"headPose\": {\"pitch\": -1.6, \"roll\": 11.2, \"yaw\": -3.5}, \"gender\": \"male\", \"age\": 21.0, \"facialHair\": {\"moustache\": 0.1, \"beard\": 0.1, \"sideburns\": 0.1}, \"glasses\": \"NoGlasses\", \"emotion\": {\"anger\": 0.0, \"contempt\": 0.0, \"disgust\": 0.0, \"fear\": 0.0, \"happiness\": 0.0, \"neutral\": 1.0, \"sadness\": 0.0, \"surprise\": 0.0}, \"blur\": {\"blurLevel\": \"low\", \"value\": 0.0}, \"exposure\": {\"exposureLevel\": \"goodExposure\", \"value\": 0.52}, \"noise\": {\"noiseLevel\": \"low\", \"value\": 0.0}, \"makeup\": {\"eyeMakeup\": true, \"lipMakeup\": true}, \"accessories\": [], \"occlusion\": {\"foreheadOccluded\": false, \"eyeOccluded\": false, \"mouthOccluded\": false}, \"hair\": {\"bald\": 0.02, \"invisible\": false, \"hairColor\": [{\"color\": \"black\", \"confidence\": 1.0}, {\"color\": \"other\", \"confidence\": 0.66}, {\"color\": \"gray\", \"confidence\": 0.65}, {\"color\": \"brown\", \"confidence\": 0.36}, {\"color\": \"blond\", \"confidence\": 0.04}, {\"color\": \"red\", \"confidence\": 0.01}]}}}]'"
      ]
     },
     "execution_count": 86,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "face_api_url = 'https://face-ll.cognitiveservices.azure.com/face/v1.0/detect'\n",
    "\n",
    "# 请求正文\n",
    "image_url = 'http://n.sinaimg.cn/ent/transform/20170305/uDHy-fycapec1583742.jpg'\n",
    "\n",
    "headers = {'Ocp-Apim-Subscription-Key': subscription_key}\n",
    "\n",
    "# 请求参数\n",
    "params = {\n",
    "    'returnFaceId': 'true',\n",
    "    'returnFaceLandmarks': 'false',\n",
    "    # 选择model\n",
    "    'recognitionModel':'recognition_02',\n",
    "    'detectionModel':'detection_01',\n",
    "    # 可选参数,请仔细阅读API文档\n",
    "    'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise',\n",
    "}\n",
    "\n",
    "response = requests.post(face_api_url, params=params,\n",
    "                         headers=headers, json={\"url\": image_url})\n",
    "# json.dumps 将json--->字符串\n",
    "json.dumps(response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5、Find similars 返回相似置信度\n",
    "- 将歌手薛之谦的照片与以上十张明星/歌手人脸进行比对\n",
    "- 参考[find similar文档](https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395237)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'persistedFaceId': '7d6ef89f-f64d-4d9e-aa6d-1e9fdc0913a0',\n",
       "  'confidence': 0.15656},\n",
       " {'persistedFaceId': 'bfd5c488-1ef9-46b5-a823-892503c6c30e',\n",
       "  'confidence': 0.15004},\n",
       " {'persistedFaceId': 'c6e7e909-4ac9-4320-89bd-df99a0657ffd',\n",
       "  'confidence': 0.09838},\n",
       " {'persistedFaceId': '0088b46e-9674-4866-a6e3-c29edabe5b74',\n",
       "  'confidence': 0.09748},\n",
       " {'persistedFaceId': '1e0f4e60-d99e-4f99-abda-3d7d33e9d7b1',\n",
       "  'confidence': 0.09333},\n",
       " {'persistedFaceId': '550d5f01-71ad-4801-8fe9-84c48f14fa8e',\n",
       "  'confidence': 0.09229},\n",
       " {'persistedFaceId': 'f5c689b4-e2b8-4c4e-aad2-14c48785e27e',\n",
       "  'confidence': 0.09058},\n",
       " {'persistedFaceId': '22fa2ee3-739d-4cd6-8442-5ed5bf4df979',\n",
       "  'confidence': 0.08981},\n",
       " {'persistedFaceId': '54f91efa-57f2-4c1d-b6f1-3e432b7c52a0',\n",
       "  'confidence': 0.08907},\n",
       " {'persistedFaceId': 'c8c72ebe-3a2b-4bf9-95e0-6c28d95b4a58',\n",
       "  'confidence': 0.08266}]"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#4、Find similars\n",
    "\n",
    "findsimilars_url = \"https://face-ll.cognitiveservices.azure.com/face/v1.0/findsimilars\"\n",
    "薛之谦 = response.json()[0][\"faceId\"]\n",
    "\n",
    "# 请求正文 faceId需要先检测一张照片获取\n",
    "data_findsimilars = {\n",
    "    \"faceId\":薛之谦,\n",
    "    \"faceListId\":\"xzq_test\",\n",
    "    \"maxNumOfCandidatesReturned\": 10,\n",
    "    \"mode\": \"matchFace\"#matchPerson\n",
    "    }\n",
    "\n",
    "r_findsimilars = requests.post(findsimilars_url,headers=headers,json=data_findsimilars)\n",
    "\n",
    "r_findsimilars.status_code\n",
    "r_findsimilars.json()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6、将人脸数据做成表格"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'persistedFaces': [{'persistedFaceId': '22fa2ee3-739d-4cd6-8442-5ed5bf4df979',\n",
       "   'userData': '许嵩'},\n",
       "  {'persistedFaceId': 'c8c72ebe-3a2b-4bf9-95e0-6c28d95b4a58',\n",
       "   'userData': '易烊千玺'},\n",
       "  {'persistedFaceId': '54f91efa-57f2-4c1d-b6f1-3e432b7c52a0',\n",
       "   'userData': '张若昀'},\n",
       "  {'persistedFaceId': '1e0f4e60-d99e-4f99-abda-3d7d33e9d7b1',\n",
       "   'userData': '张新成'},\n",
       "  {'persistedFaceId': '550d5f01-71ad-4801-8fe9-84c48f14fa8e',\n",
       "   'userData': '李现'},\n",
       "  {'persistedFaceId': '7d6ef89f-f64d-4d9e-aa6d-1e9fdc0913a0',\n",
       "   'userData': '大张伟'},\n",
       "  {'persistedFaceId': 'bfd5c488-1ef9-46b5-a823-892503c6c30e',\n",
       "   'userData': '朱桢'},\n",
       "  {'persistedFaceId': 'c6e7e909-4ac9-4320-89bd-df99a0657ffd',\n",
       "   'userData': '刘维'},\n",
       "  {'persistedFaceId': 'f5c689b4-e2b8-4c4e-aad2-14c48785e27e',\n",
       "   'userData': '高磊鑫'},\n",
       "  {'persistedFaceId': '0088b46e-9674-4866-a6e3-c29edabe5b74',\n",
       "   'userData': '何炅'}],\n",
       " 'faceListId': 'xzq1',\n",
       " 'name': 'xzq_find_similar',\n",
       " 'userData': '薛之谦和谁最像？'}"
      ]
     },
     "execution_count": 88,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 使用pandas\n",
    "import pandas as pd\n",
    "get_facelist_url = \"https://face-ll.cognitiveservices.azure.com/face/v1.0/facelists/{faceListId}\"\n",
    "\n",
    "data = {\n",
    "    \"faceListId\":\"xzq_test\",\n",
    "}\n",
    "\n",
    "r_get_facelist = requests.get(get_facelist_url,headers=headers,params=data)\n",
    "r_get_facelist.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>persistedFaceId</th>\n",
       "      <th>userData</th>\n",
       "      <th>confidence</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>7d6ef89f-f64d-4d9e-aa6d-1e9fdc0913a0</td>\n",
       "      <td>大张伟</td>\n",
       "      <td>0.15656</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>bfd5c488-1ef9-46b5-a823-892503c6c30e</td>\n",
       "      <td>朱桢</td>\n",
       "      <td>0.15004</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>c6e7e909-4ac9-4320-89bd-df99a0657ffd</td>\n",
       "      <td>刘维</td>\n",
       "      <td>0.09838</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>0088b46e-9674-4866-a6e3-c29edabe5b74</td>\n",
       "      <td>何炅</td>\n",
       "      <td>0.09748</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1e0f4e60-d99e-4f99-abda-3d7d33e9d7b1</td>\n",
       "      <td>张新成</td>\n",
       "      <td>0.09333</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>550d5f01-71ad-4801-8fe9-84c48f14fa8e</td>\n",
       "      <td>李现</td>\n",
       "      <td>0.09229</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>f5c689b4-e2b8-4c4e-aad2-14c48785e27e</td>\n",
       "      <td>高磊鑫</td>\n",
       "      <td>0.09058</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>22fa2ee3-739d-4cd6-8442-5ed5bf4df979</td>\n",
       "      <td>许嵩</td>\n",
       "      <td>0.08981</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>54f91efa-57f2-4c1d-b6f1-3e432b7c52a0</td>\n",
       "      <td>张若昀</td>\n",
       "      <td>0.08907</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>c8c72ebe-3a2b-4bf9-95e0-6c28d95b4a58</td>\n",
       "      <td>易烊千玺</td>\n",
       "      <td>0.08266</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                        persistedFaceId userData  confidence\n",
       "5  7d6ef89f-f64d-4d9e-aa6d-1e9fdc0913a0      大张伟     0.15656\n",
       "6  bfd5c488-1ef9-46b5-a823-892503c6c30e       朱桢     0.15004\n",
       "7  c6e7e909-4ac9-4320-89bd-df99a0657ffd       刘维     0.09838\n",
       "9  0088b46e-9674-4866-a6e3-c29edabe5b74       何炅     0.09748\n",
       "3  1e0f4e60-d99e-4f99-abda-3d7d33e9d7b1      张新成     0.09333\n",
       "4  550d5f01-71ad-4801-8fe9-84c48f14fa8e       李现     0.09229\n",
       "8  f5c689b4-e2b8-4c4e-aad2-14c48785e27e      高磊鑫     0.09058\n",
       "0  22fa2ee3-739d-4cd6-8442-5ed5bf4df979       许嵩     0.08981\n",
       "2  54f91efa-57f2-4c1d-b6f1-3e432b7c52a0      张若昀     0.08907\n",
       "1  c8c72ebe-3a2b-4bf9-95e0-6c28d95b4a58     易烊千玺     0.08266"
      ]
     },
     "execution_count": 89,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 制成表格 查看“薛之谦和谁最像？”\n",
    "adf = pd.json_normalize(r_get_facelist.json()[\"persistedFaces\"])\n",
    "adf\n",
    "\n",
    "bdf = pd.json_normalize(r_findsimilars.json())\n",
    "bdf\n",
    "\n",
    "pd.merge(adf, bdf,how='inner', on='persistedFaceId').sort_values(by=\"confidence\",ascending = False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
